package com.example.teacher.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.servicebase.client.VodClient;
import com.example.teacher.entity.EduVideo;
import com.example.teacher.mapper.EduVideoMapper;
import com.example.teacher.service.EduVideoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.netty.util.internal.StringUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程视频 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2022-05-25
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class EduVideoServiceImpl extends ServiceImpl<EduVideoMapper, EduVideo> implements EduVideoService {
    @Autowired
    private VodClient client;
    @Override
    public void removeByCourseId(String courseId) {
        //根据课程id删除小节
        QueryWrapper<EduVideo> wrapper =new QueryWrapper<>();
        wrapper.eq("course_id",courseId);
        //先查询出该课程拥有的所有小节
        List<EduVideo> videoList = baseMapper.selectList(wrapper);
        List<String> list = new ArrayList<>();
//        循环删除所有小节的视频
        for (EduVideo eduVideo : videoList) {
            //拿到视频id
            String videoId = eduVideo.getVideoSourceId();
            if (!StringUtil.isNullOrEmpty(videoId)) {
//                不为空则执行远程调用删除视频 否则会报错
                list.add(videoId);
            }
        }
        //包装成 id,id,id的样子
        String videoIds = StringUtils.join(list.toArray(), ",");
        //如果一个视频都没有，那么就不用发起请求删除视频
        if (!StringUtil.isNullOrEmpty(videoIds)) {
            //一次请求批量删除
            client.removeVideo(videoIds);
        }
        //最后删除数据库中该课程所有的小节
        baseMapper.delete(wrapper);
    }
}
